<template>
  <a-drawer width="800px" :open="true" :title="`${item ? '编辑' : '添加'}机源信息`" @close="onClose">

    <template #extra>
      <a-space>
        <a-button type="primary" @click="toSave" :loading="saving">保存</a-button>
      </a-space>
    </template>

    <a-spin :spinning="loading">
      <a-form ref="formRef" :model="formState" layout="vertical" :rules="rules" v-if="!loading">

        <a-card title="基础信息" size="small">
          <a-row :gutter="16">

            <a-col :span="24">

              <a-form-item label="停放位置" name="parkPlace" :autoLink="false">
                <ProvinceCitySelect :value="formState.parkPlace" @update:value="onUpdatePlace" />
                <!-- <AddressSelect :value="formState.parkPlace" @update:value="onUpdateAddress" /> -->
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="名称" name="name">
                <a-input v-model:value="formState.name" placeholder="请输入" />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="吨位" name="tonnage">
                <a-input-number v-model:value="formState.tonnage" placeholder="请输入" />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item label="商户" name="storeId" :autoLink="false">
                <a-button @click="toChooseStore" class="mr">选择</a-button>
                <StoreLink :item="formState.store" v-if="formState.store" />
                <!-- <StoreSelect :filter="storeFilter" @update:value="onStoreIdChange" /> -->
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="品牌" name="brandId">
                <a-button @click="toChooseBrand" class="mb">选择</a-button>
                <BrandLink :id="formState.brandId" v-if="formState.brandId" />
              </a-form-item>
            </a-col>
          </a-row>
        </a-card>

        <a-card title="销售信息" class="mt" size="small">
          <a-row :gutter="16">
            <a-col :span="8">
              <a-form-item label="售价" name="price">
                <a-input-number :min="0" :max="99999" :precision="2" v-model:value="formState.price" placeholder="请输入">
                  <template #addonAfter>万元</template>
                </a-input-number>
              </a-form-item>
            </a-col>
            <a-col :span="16">
              <a-space>
                <a-form-item label="可议价" name="priceReduce">
                  <a-switch v-model:checked="formState.priceReduce" checked-children="是" un-checked-children="否" />
                </a-form-item>
                <a-form-item label="可租赁" name="rentable">
                  <a-switch v-model:checked="formState.rentable" checked-children="是" un-checked-children="否" />
                </a-form-item>
              </a-space>
            </a-col>
          </a-row>
          <a-row v-if="formState.rentable" :gutter="16">
            <a-col :span="8">
              <a-form-item label="租赁价格" name="rentPrice">
                <a-input-number :min="0" :max="999" :precision="2" v-model:value="formState.rentPrice"
                  placeholder="请输入">
                  <template #addonAfter>万/月</template>
                </a-input-number>
              </a-form-item>
            </a-col>
            <a-col :span="16">
              <a-form-item label="带机手" name="rentDriver">
                <a-switch v-model:checked="formState.rentDriver" checked-children="是" un-checked-children="否" />
              </a-form-item>
            </a-col>
          </a-row>
        </a-card>

        <a-card title="属性信息" class="mt" size="small">
          <a-row :gutter="16">
            <a-col :span="8">
              <a-form-item label="表显小时数" name="hours">
                <a-input-number :min="0" :max="9999999" v-model:value="formState.hours" placeholder="请输入">
                  <template #addonAfter>小时</template>
                </a-input-number>
              </a-form-item>
            </a-col>
            <a-col :span="16">
              <a-form-item label="出厂时间" name="deliveryDateObj">
                <a-date-picker v-model:value="formState.deliveryDateObj" />
              </a-form-item>
            </a-col>
          </a-row>

          <a-divider>更多属性</a-divider>
          <a-row :gutter="16">
            <a-col :span="8" v-for="(prop, index) in itemProps" :key="index">
              <a-form-item :autoLink="false" :label="prop.name">

                <a-input v-if="prop.type == 'text'" :value="prop.value || prop.defaultValue"
                  @change="e => setPropValue(e, index)" />
                <a-input-number v-else-if="prop.type == 'number'" :value="prop.value || prop.defaultValue"
                  @change="e => setPropValue(e, index)" />
                <DictSelect v-else-if="prop.type == 'dict'" :value="prop.value || prop.defaultValue"
                  @update:value="value => setPropValue({ target: { value } }, index)" :code="prop.dictCode" />
              </a-form-item>
            </a-col>
          </a-row>

        </a-card>

        <a-card title="图片视频" class="mt" size="small">
          <a-upload :multiple="true" accept="image/*,video/*" v-model:file-list="fileList" list-type="picture-card"
            :before-upload="beforeUpload">
            <div>
              <plus-outlined />
              <div style="margin-top: 8px">上传</div>
            </div>
          </a-upload>
        </a-card>
        <a-card title="备注" class="mt" size="small">
          <a-form-item name="remark">
            <a-textarea v-model:value="formState.remark" placeholder="请输入" />
          </a-form-item>
        </a-card>

      </a-form>
    </a-spin>
  </a-drawer>
  <StoreSelectModal :filter="storeFilter" v-if="modal == 'store'" @close="onCancel" @select="onSelectStore" />
  <BrandSelectModal :id="formState.brandId" v-if="modal == 'brand'" @close="onCancel" @select="onSelectBrand" />
</template>

<script setup>
import { reactive, onMounted, ref, computed } from 'vue'
import { saveItem, getItemById } from '@/api/item';
import { listProps } from '@/api/props';
import { message } from 'ant-design-vue'
import { confirm } from '@/mixin'
import { uploadFiles, getFile } from '@/api/att';
import DictSelect from './DictSelect.vue'
import StoreLink from './StoreLink.vue'
import StoreSelectModal from './StoreSelectModal.vue'
import BrandSelectModal from './BrandSelectModal.vue'
import BrandLink from './BrandLink.vue'
import dayjs from 'dayjs'
import ProvinceCitySelect from './ProvinceCitySelect.vue';

const props = defineProps(['id'])
const emit = defineEmits(['close', 'saved'])

const rules = {
  parkPlace: [
    { required: true, message: '请选择停放位置' }
  ],
  name: [
    { required: true, message: '请输入配置名称' }
  ],
  storeId: [
    { required: true, message: '请选择归属商家', trigger: 'change' }
  ],
  price: [
    { required: true, message: '请输入销售价格' }
  ],
  hours: [
    { required: true, message: '请输入表显小时数' }
  ],
  deliveryDateObj: [
    { required: true, message: '请选择出厂时间' }
  ],
}

const modal = ref(false)
const loading = ref(false)
const item = ref(null)
const formRef = ref(null)
const formState = reactive({})
const saving = ref(false)
const fileList = ref([])

const itemProps = reactive([])

const storeFilter = computed(() => {
  const rs = {}

  if (formState.parkProvince) {
    rs['province'] = formState.parkProvince
  }
  return rs
})

onMounted(() => {
  getItem() 
})

const getProps = async () => {
  const res = await listProps({ size: 1000 })
  const arr = (res.data.records || []).map(i=>{
    if(item.value){
      const keys = Object.keys(item.value.props)
      for(let key of keys){
        if(i.name == key){
          i.value = item.value.props[key]
        }
      }
    }    
    return i;
  })
  itemProps.push(...arr)
}
const getItem = async () => {
  if (props.id) {
    loading.value = true
    const res = await getItemById(props.id)
    loading.value = false
    item.value = res.data
    parseItem()
  }
  getProps()
}

const setPropValue = (e, index) => {
  itemProps[index].value = e.target.value
}

const parseItem = () => {
  const it = item.value
  if (it) {

    formState.name = it.name
    formState.storeId = it.storeId
    formState.brandId = it.brandId
    formState.store = it.store
    formState.parkProvince = it.parkProvince
    formState.parkCity = it.parkCity
    formState.parkDistrict = it.parkDistrict
    formState.parkAdcode = it.parkAdcode
    if (it.parkProvince) {
      formState.parkPlace = [it.parkProvince, it.parkCity, it.parkDistrict]
    } else {
      formState.parkPlace = null
    }

    formState.price = it.price
    formState.priceReduce = it.priceReduce
    formState.rentable = it.rentable
    formState.rentPrice = it.rentPrice
    formState.rentDriver = it.rentDriver
    formState.hours = it.hours
    formState.tonnage = it.tonnage
    formState.remark = it.remark
    if (it.deliveryDate) {
      formState.deliveryDateObj = dayjs(it.deliveryDate)
    }
    if (it.medias && it.medias.length > 0) {
      fileList.value = it.medias.map(i => {
        return {
          id: i.id,
          mime: i.mime,
          name: i.name,
          size: i.fileSize,
          url: getFile(i.id)
        }
      })
    }
  } else {
    formState.name = null
    formState.storeId = null
    formState.brandId = null
    formState.tonnage = 2
    formState.parkProvince = null
    formState.parkCity = null
    formState.parkDistrict = null
    formState.parkAdcode = null
    formState.parkPlace = null
    formState.price = null
    formState.priceReduce = null
    formState.rentable = null
    formState.rentPrice = null
    formState.rentDriver = null
    formState.hours = null
    formState.remark = null
    formState.deliveryDateObj = null

    fileList.value = []
  }
}

const onUpdatePlace = (arr) => {
  formState.parkProvince = arr[0]
  formState.parkCity = arr[1]
  formState.parkPlace = arr
}

const onUpdateAddress = (e) => {
  console.log(e)

  formState.parkPlace = e;

  const { province, city, district } = e

  formState.parkProvince = province.name
  formState.parkCity = city.name
  formState.parkDistrict = district.name
  formState.parkAdcode = district.id

  // formState.storeId = null

}

const onStoreIdChange = id => {
  formState.storeId = id;
}

const onClose = () => {
  emit('close')
}

const toSave = () => {
  formRef.value.validate().then(values => {

    if (fileList.length == 0) {
      message.warn('请上传机源图片或视频，至少一张')
      return
    }

    confirm('您确定要保存机源信息吗?', async () => {
      if (item.value) {
        values.id = item.value.id
      }
      let ado = values.parkPlace
      if (ado) {

        values.parkProvince = ado[0]
        values.parkCity = ado[1]
        // 移除属性
        delete values.parkPlace
      }
      if (values.deliveryDateObj) {
        values.deliveryDate = values.deliveryDateObj.format('YYYY-MM-DD')
        // 移除属性
        delete values.deliveryDateObj
      }

      const propsMap = {}

      itemProps.forEach(i => {
        propsMap[i.name] = i.value || i.defaultValue
      })

      values.props = propsMap;

      saving.value = true

      // 先上传附件
      const origin = fileList.value.filter(i => i.id)
      const files = fileList.value.filter(i => i.originFileObj).map(i => i.originFileObj)
      let atts = [...origin]
      if (files.length > 0) {
        const arr = await uploadFiles(files)
        atts.push(...arr)
      }
      values.medias = atts

      const res = await saveItem(values)
      saving.value = false
      if (res.data) {
        message.success('保存成功')
        emit('saved')
      } else {
        message.error('保存失败')
      }
    })
  }).catch(e => {
    const { errorFields } = e
    errorFields.forEach(e => {
      message.warn(e.errors.join(','))
    })
  })
}

const beforeUpload = file => {
  return false;
}

const onCancel = () => {
  modal.value = null;
}

const toChooseStore = () => {
  modal.value = 'store'
}
const toChooseBrand = () => {
  modal.value = 'brand'
}
const onSelectStore = (arr) => {
  if (arr.length > 0) {
    const store = arr[0];
    formState.store = store;
    formState.storeId = store.id;
  }
  modal.value = null
}
const onSelectBrand = (e) => {
  modal.value = null
  formState.brandId = e.id
}

</script>

<style lang="less" scoped></style>